<template>
	<div>
		<div class="crumbs">
			<el-breadcrumb separator="/">
				<el-breadcrumb-item>
					<i class="el-icon-lx-cascades"></i> 日志管理
				</el-breadcrumb-item>
			</el-breadcrumb>
		</div>
		<div class="container">
			<div class="handle-box">
				<el-button type="primary" icon="el-icon-delete" class="handle-del mr10" @click="delAllSelection">批量删除</el-button>
				<el-input v-model="query.account" placeholder="账号" class="handle-input mr10"></el-input>
				<el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
				<!-- <el-button type="danger" icon="el-icon-plus" @click="handleAdd">添加</el-button> -->
			</div>
			<el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header"
			 @selection-change="handleSelectionChange"  style="min-height:400px">
				 <el-table-column type="selection" width="55" align="center"></el-table-column>
				<el-table-column prop="id" label="ID" width="120" align="center"></el-table-column>
				<el-table-column prop="account" label="用户" width="160"></el-table-column>
				<el-table-column prop="ip" label="ip地址" width="260" align="center"></el-table-column>
				<el-table-column prop="loginTime"  label="登录日期" align="center" :formatter="dateFormat"></el-table-column>
				<el-table-column label="操作" width="180" align="center">
					<template slot-scope="scope">
						<el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
						<el-button type="text" icon="el-icon-delete" class="red" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div class="pagination">
				<el-pagination background layout="total, sizes, prev, pager, next, jumper" :current-page="query.pageIndex"
				 :page-size="query.pageSize" :total="recordTotal" @current-change="handlePageChange" @size-change="handleSizeChange"></el-pagination>
			</div>
		</div>

		<!-- 添加弹出框 -->
		<!-- <el-dialog title="添加" :visible.sync="addVisible" width="30%">
			<el-form ref="form" :model="form" label-width="110px">
				<el-form-item label="账号" >
					<el-input v-model="form.title"></el-input>
				</el-form-item>
				<el-form-item label="作者">
					<el-input v-model="form.author"></el-input>
				</el-form-item>
				<el-form-item label="内容">
					<el-input type="textarea" v-model="form.content"  :autosize="{ minRows: 3, maxRows: 2}"></el-input>
				</el-form-item>
				<el-form-item label="状态">
					<el-switch v-model="form.state" active-text="正常" inactive-text="禁用" active-value="1" inactive-value="0">
					</el-switch>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="addVisible = false">取 消</el-button>
				<el-button type="primary" @click="saveAdd">确 定</el-button>
			</span>
		</el-dialog> -->

		<!-- 编辑弹出框 -->
		<el-dialog title="编辑" :visible.sync="editVisible" width="30%">
			<el-form ref="form" :model="form" label-width="70px">
				<el-form-item label="用户">
					<el-input v-model="form.account"></el-input>
				</el-form-item>
				<el-form-item label="ip地址">
					<el-input v-model="form.ip"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="editVisible = false">取 消</el-button>
				<el-button type="primary" @click="saveEdit">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	/* import { fetchData } from '../../index'; */
	import axios from 'axios';
	import moment from 'moment';

	export default {
		name: 'basetable',
		data() {
			return {
				query: {
					account: '',
					pageIndex: 1, //分页页面索引
					pageSize: 10 //每页面显示的记录数,默认显示10条
				},
				tableData: [],
				multipleSelection: [],
				delList: [],
				// addVisible: false,
				editVisible: false,
				pageTotal: 0,
				recordTotal: 0,
				form: {},
				idx: -1,
				id: -1,
				instance: null, //请求实例对象
				searchVisiable: false //搜索状态
			};
		},
		created() {
			this.getUserData(this.query.pageIndex, this.query.pageSize);
		},
		methods: {
			//定义拦截器方法
			interceptor() {
				console.log('请求拦截器调用')
				// 添加请求拦截器，在请求头中加token
				axios.interceptors.request.use(
					config => { //请求成功时，对请求作拦截处理
						if (localStorage.getItem('Authorization')) {
							console.log('读取token,并加入请求头')
							config.headers.Authorization = localStorage.getItem('Authorization');
							console.log(config)
						} else {
							console.log('读取token失败')
						}
						console.log('请求拦截器修改token')
						return config;
					},
					error => { //请求失败时
						return Promise.reject(error);
					});
			},

			getUserData(pageIndex, pageSize) { 
				axios.get('/api/loginfo/page', {
					params: {
						pages: pageIndex,
						size: pageSize
					}
				}).then(res => { //请求成功，返回数据
					console.log(res)
					this.tableData = res.data.data.list; //绑定数据到模型数据
					this.pageTotal = res.data.data.pageTotal;
					this.recordTotal = res.data.data.recordTotal;
				}).catch(err => { //错误处理
					console.log(err)
				})
			},

			// 触发搜索按钮
			handleSearch() {
				//修改搜索状态，在分页时将调用搜索列表方法
				this.searchVisiable = true;
				//搜索第1页
				this.searchListPages(1);
			},
			searchListPages(val) {
				//搜索并请求分页数据
				axios.get('/api/loginfo/search', {
					params: {
						pages: val,
						size: this.query.pageSize,
						account: this.query.account
					}
				}).then(res => { //请求成功，返回数据
					console.log(res)
					this.tableData = res.data.data.list; //绑定数据到模型数据
					this.pageTotal = res.datga.data.pageTotal;
					this.recordTotal = res.data.data.recordTotal;
					
				}).catch(err => { //错误处理
					console.log(err)
				})

			},
			// 删除操作
			handleDelete(index, row) {
				//修改搜索状态，在分页时将调用分页列表方法
				this.searchVisiable = false;
				console.log(row)
				// 二次确认删除
				this.$confirm('确定要删除吗？', '提示', {
						type: 'warning'
					})
					.then(() => {
						this.tableData.splice(index, 1); //从数据模型中删除
						//发送请求，从数据库中删除数据行row
						axios.delete('/api/loginfo/delete', {
							params: {
								id: row.id //row为一条页面数据
							}
						}).then(res => {
							//console.log(res);
							if (res.data.data) { //为true
								this.$message.success('成功删除1条数据');
							} else {
								this.$message.success('删除数据失败');
							}
						}).catch(err => {
							this.$message.success('删除数据失败');
						})
					})
					.catch(() => {});
			},
			// 多选操作
			handleSelectionChange(val) {
				//console.log(val)
				this.multipleSelection = val;
			},
			//批量删除数据
			delAllSelection() {
				//修改搜索状态，在分页时将调用分页列表方法
				this.searchVisiable = false;
				const length = this.multipleSelection.length;
				//this.delList = this.delList.concat(this.multipleSelection);

				//拼接要删除的数据名称
				for (let i = 0; i < length; i++) {
					//str += this.multipleSelection[i].name + ' ';
					//添加要删除的数据id
					this.delList.push(this.multipleSelection[i].id);
				}
				console.log(this.delList)
				//后端删除对应数据            
				axios.delete('/api/loginfo/deleteAll', {
						data: {
							list: this.delList
						}
					})
					.then(res => {
						console.log(res)
						if (res.data.data) { //为true
							this.$message.success('成功删除数据' + length + '条');
						} else {
							this.$message.success('删除数据失败');
						}
					})
				this.multipleSelection = [];
				//分页查询当前索引页面
				this.handlePageChange(this.query.pageIndex)
			},
			//添加操作
			// handleAdd() {
			// 	this.addVisible = true;
			// },
			// saveAdd() {
			// 	let that = this;
			// 	axios({
			// 		method: 'post',
			// 		url: '/api/loginfo/save', //带token验证
			// 		data: that.form //提交json格式数据
			// 	}).then(res => { //请求成功时
			// 		//判断json对象为空，Object.keys(res.data.message).length!=0
			// 		console.log(res)
			// 		if (res.data.code == 200) {
			// 			that.$message.success('添加成功');
			// 			that.idx = -1;
			// 			that.form = {}
			// 		} else { //返回空对象时
			// 			console.log(res)
			// 			that.$message.error('添加失败');
			// 		}
			// 	}).catch(err => {
			// 		console.log(err)
			// 		that.$message.error('添加失败！')
			// 	})
			// 	this.addVisible = false;
			// },
			// 编辑操作
			handleEdit(index, row) {
				this.idx = index; //编辑数据的索引
				this.form = row;
				this.editVisible = true;
				console.log(index)
			},
			// 保存编辑
			saveEdit() {
				if (this.idx > -1) { //编辑数据
					//修改搜索状态，在分页时将调用分页列表方法
					this.searchVisiable = false;
					this.editVisible = false;
					var data = this.form;
					this.interceptor();
					axios.put('/api/loginfo/update', data).then(res => {
						console.log("数据更新成功")
						this.$set(this.tableData, this.idx, this.form);
						this.$message.success(`修改第 ${this.idx + 1} 行成功`);
						this.idx = -1;
						this.form = {}
					}).catch(err => {
						console.log(err)
						this.idx = -1;
						this.form = {}
					})
				} else { //新建
				this.$message.error("编辑失败！");
					this.editVisible = false;
				}
			},
			// 分页
			// 分页导航
			handlePageChange(val) { //val为页码索引      	

				if (this.searchVisiable) { //是搜索分页
					this.searchListPages(val)
				} else { //是列表分页
					this.query.pageIndex = val;
					var pageSize = this.query.pageSize;
					//按页码、每页记录数，请求数据
					this.getUserData(val, pageSize);
				}
			},
			// 每页显示的条数
			handleSizeChange(val) {
				// 改变每页显示的条数 
				this.query.pageSize = val
				// 点击每页显示的条数时【10，20】，显示第一页
				this.getUserData(1, val)
				// 注意：在改变每页显示的条数时，要将页码显示到第一页
				this.query.pageIndex = 1
			},
			//添加用户
			// addUser() {
			// 	//修改搜索状态，在分页时将调用分页列表方法
			// 	this.searchVisiable = false;
			// 	//状态更新后，调用saveEdit()方法，添加用户
			// 	this.editVisible = true;
			// 	console.log("添加数据")
			// 	//this.saveEdit();
			// },
			//日期格式处理
			dateFormat(row, column, cellValue, index) {
				var date = cellValue
				if (!date) {
					return ''
				}
				return moment(date).format('YYYY年MM月DD日 HH:mm:ss')
			}
		}
	};
</script>

<style scoped>
	.handle-box {
		margin-bottom: 20px;
	}

	.handle-select {
		width: 120px;
	}

	.handle-input {
		width: 300px;
		display: inline-block;
	}

	.table {
		width: 100%;
		font-size: 14px;
	}

	.red {
		color: #ff0000;
	}

	.mr10 {
		margin-right: 10px;
	}

	.table-td-thumb {
		display: block;
		margin: auto;
		width: 40px;
		height: 40px;
	}
	
</style>
